import React, { createContext, useContext, useState } from 'react';
import { View, Text } from '@tarojs/components';
import './index.scss';

interface TabsContextValue {
  activeTab: string;
  setActiveTab: (value: string) => void;
}

const TabsContext = createContext<TabsContextValue>({
  activeTab: '',
  setActiveTab: () => {},
});

interface TabsProps {
  defaultValue: string;
  children: React.ReactNode;
  className?: string;
}

export const Tabs = ({ defaultValue, children, className }: TabsProps) => {
  const [activeTab, setActiveTab] = useState(defaultValue);

  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      <View className={`tabs ${className}`}>
        {children}
      </View>
    </TabsContext.Provider>
  );
};

interface TabsListProps extends React.ComponentPropsWithoutRef<typeof View> {
  children: React.ReactNode;
  className?: string;
}

export const TabsList = React.forwardRef<any, TabsListProps>(({ children, className }, ref) => {
  return (
    <View
      ref={ref}
      className={`tabs-list ${className}`}
    >
      {children}
    </View>
  );
});

interface TabsTriggerProps extends React.ComponentPropsWithoutRef<typeof View> {
  value: string;
  children: React.ReactNode;
  className?: string;
}

export const TabsTrigger = React.forwardRef<any, TabsTriggerProps>(({ value, children, className }, ref) => {
  const { activeTab, setActiveTab } = useContext(TabsContext);
  const isActive = activeTab === value;

  return (
    <View
      ref={ref}
      className={`tabs-trigger ${isActive ? 'tabs-trigger--active' : ''} ${className}`}
      onClick={() => setActiveTab(value)}
    >
      <Text className="text-sm font-medium">{children}</Text>
    </View>
  );
});

interface TabsContentProps extends React.ComponentPropsWithoutRef<typeof View> {
  value: string;
  children: React.ReactNode;
  className?: string;
}

export const TabsContent = React.forwardRef<any, TabsContentProps>(({ value, children, className }, ref) => {
  const { activeTab } = useContext(TabsContext);
  const isActive = activeTab === value;

  return isActive ? (
    <View ref={ref} className={`tabs-content ${className}`}>
      {children}
    </View>
  ) : null;
});
